package com.welike.shibo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.welike.shibo.eneity.JsonResult;
import com.welike.shibo.eneity.SysUser;
import com.welike.shibo.enums.ResultEnum;
import com.welike.shibo.exception.BaseException;
import com.welike.shibo.mapper.SysUserMapper;
import com.welike.shibo.mapper.SysUserRoleMapper;
import com.welike.shibo.service.SysPermissionService;
import com.welike.shibo.service.SysUserService;
import com.welike.shibo.utils.Constants;
import com.welike.shibo.utils.PageUtil;
import com.welike.shibo.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fangyu
 * @date 2019/11/21
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public SysUser login(String username, String password) throws NoSuchAlgorithmException {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new BaseException(ResultEnum.USERNAME_PASSWORD_IS_EMPTY);
        }
        SysUser admin = sysUserMapper.login(username, password);
        log.info("adminMapper login ==> {}", admin);
        if (null == admin) {
            log.info("用户名或者密码错误");
            throw new BaseException(ResultEnum.USERNAME_PASSWORD_ERROR);
        }
        return admin;
    }

    /**
     * 根据用户名和密码查询对应的用户
     */
    @Override
    public JSONObject getUser(String username, String password) {
        return sysUserMapper.getUser(username, password);
    }


    @Override
    public JsonResult getInfo() {
        Session session = SecurityUtils.getSubject().getSession();
        log.info("session ==> {}", session);
        SysUser sysUser = (SysUser) session.getAttribute(Constants.SESSION_USER_INFO);
        log.info("userInfo ==> {}", sysUser);
        String username = sysUser.getUsername();
        Map<String, Object> result = new HashMap<>();
        JSONObject userPermission = sysPermissionService.getUserPermission(username);
        session.setAttribute(Constants.SESSION_USER_PERMISSION, userPermission);
        result.put("userPermission", userPermission);
        return ResultUtils.success(result);
    }

    @Override
    public JsonResult logout() {
        try {
            Subject currentUser = SecurityUtils.getSubject();
            currentUser.logout();
        } catch (Exception e) {
        }
        return ResultUtils.success("成功退出登录!");
    }

    @Override
    public JsonResult listUser(Integer pageNum, Integer pageSize) {
        int count = sysUserMapper.countSysUser();
        List<JSONObject> list = sysUserMapper.listUser(PageUtil.ResetLimit(pageNum, pageSize), pageSize);
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("totalCount", count);
        result.put("totalPage", PageUtil.getPageCounts(pageSize, count));
        return ResultUtils.success(result);
    }

    @Transactional(rollbackFor = Exception.class)
    @SuppressWarnings("unchecked")
    @Override
    public JsonResult addUser(JSONObject requestJson) {
        int exist = sysUserMapper.queryExistUsername(requestJson);
        if (exist > 0){
            return ResultUtils.error(ResultEnum.E_2002);
        }
        sysUserMapper.addUser(requestJson);
        Integer uid = sysUserMapper.queryUidByUsername(requestJson);
        // 添加用户和角色绑定关系
        log.info("uid ==> {}", uid);
        sysUserRoleMapper.addUserRole(uid, requestJson.getIntValue("roleId"));
        return ResultUtils.success("添加成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @SuppressWarnings("unchecked")
    @Override
    public JsonResult updateUser(JSONObject requestJson) {
        sysUserMapper.updateUser(requestJson);
        sysUserRoleMapper.updateUserRole(requestJson);
        return ResultUtils.success("更新成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @SuppressWarnings("unchecked")
    @Override
    public JsonResult deleteUser(JSONObject requestJson) {
        sysUserMapper.deleteById(requestJson);
        sysUserRoleMapper.deleteByUid(requestJson);
        return ResultUtils.success("删除成功");
    }
}
